from datetime import datetime, timedelta
import jwt
from flask import current_app, g


def generate_token(payload, expire, secret=None):
    """
    生成token
    :return:
    """
    _payload = {
        'exp': expire
    }
    # 更新荷载信息
    _payload.update(payload)
    if not secret:
        secret = current_app.config.get('JWT_SECRET')
    token = jwt.encode(_payload, secret, algorithm='HS256')
    return token


def verify_jwt(token, secret=None):
    """
    验证token
    """
    if not secret:
        secret = current_app.config["JWT_SECRET"]
    try:
        payload = jwt.decode(token, secret, algorithms='HS256')
    except:
        payload = None
    return payload


def create_login_token(user_id, refresh=True):
    """
    用户登录，返回token、refresh_token
    """
    # 定义过期时间
    expiry = datetime.utcnow() + timedelta(hours=2)
    token = generate_token({"user_id": user_id}, expiry)
    if refresh:
        exp = datetime.utcnow() + timedelta(days=15)
        refresh_token = generate_token({"user_id": user_id, 'is_refresh': True}, exp)
    else:
        refresh_token = None
    return token, refresh_token


def refresh_token():
    """
    无感刷新token
    """
    if g.user_id and g.refresh is True:
        token, refresh_token = create_login_token(g.user_id, refresh=False)
        return token
    return ''
